import axios from 'axios'
import QS from 'qs'
import Vue from 'vue'
import router from '../router/index'
import store from '../store/index'

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

// 请求超时时间
axios.defaults.timeout = 8000

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 显示loading加载
    if (store.state.isLoading) {
      // 更改loading的值
      store.commit('setLoading', true)
    }
    // token验证
    if (store.state.token) {
      config.headers.Authorization = store.state.token
    }
    return config
  },
  error => {
    store.commit('setLoading', false)
    return Promise.error(error)
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    store.commit('setLoading', false)
    if (response.status === 200) {
      return Promise.resolve(response)
    }
  },
  error => {
    let res = error.response
    switch (Number(res.status)) {
      case 400:
        Vue.prototype.$toast.fail('操作失败')
        break

      case 404:
        Vue.prototype.$toast.fail('请求不存在')
        break

      case 408:
        Vue.prototype.$toast.fail('请求超时')
        break

      case 500:
        Vue.prototype.$toast.fail('内部服务器错误')
        break
    }
    store.commit('setLoading', false)
    return Promise.reject(error)
  }
);

/**
 * 封装url传参的请求方法
 * url: 路径
 * method: 请求方式,get和post居多
 * params: 传递的参数
 */
const get = async (url, method, params) => {
  const res = await axios(url, {
    baseURL: store.state.baseURL,
    method: method,
    params: params,
    /**
       * 负责序列化`params`的可选函数
       */
    paramsSerializer: function (params) {
      return QS.stringify(params, { arrayFormat: 'brackets' })
    }
  }).catch(err => {
    store.commit('setLoading', false)
    if (!err.response) {
      Vue.prototype.$toast.fail('网络错误')
    }
    return Promise.reject(err.response ? err.response.data : undefined)
  })
  return Promise.resolve(res.data)
}

/**
 * 封装post请求
 * url: 路径
 * params: 传递的参数
 */
const post = async (url, params) => {
  const res = await axios.post(`${store.state.baseURL}${url}`, params).catch(err => {
    store.commit('setLoading', false)
    if (!err.response) {
      Vue.prototype.$toast.fail('网络错误')
    }
    return Promise.reject(err.response ? err.response.data : undefined)
  })
  return Promise.resolve(res.data)
}

export default async (url, method, params = {}) => {
  let res = {}
  if (method == 'GET') {
    res = await get(url, method, params)
  } else if (method == 'POST') {
    res = await post(url, params)
  }
  if (res.status == 401) {
    Vue.prototype.$toast("请重新绑定手机号")
    store.commit('signOut')
    router.replace('/index')
    return Promise.reject(res)
  }
  return Promise.resolve(res)
}
